import { qrLandPrefix } from "../../utils/constant"

// pages/land/land.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    if (!options) {
      options = {};
    }
    if (options.q) {
      let q = decodeURIComponent(options.q);
      if (q.startsWith(qrLandPrefix)) {
        options = this.parseParam(q.substring(qrLandPrefix.length));
      }
    }
    let path = options.path;
    let query = options.query;
    let channel = options.channel;
    if (!path) {
      path = '/pages/index/index';
    }
    let url = path;
    if (query) {
      url = path + '?' + query;
    }
    if (channel) {
      getApp().globalData.channel = channel;
    }
    wx.showLoading({
      title: "加载中"
    });
    wx.redirectTo({
      url: url,
    }).catch(() => {
      wx.switchTab({
        url: url
      })
    })
  },
  parseParam(query: string): any {
    if (query.startsWith('?')) {
      return this.parseParam(query.substring(1));
    }
    let result: any = {};
    let array = query.split('&');
    if (array.length === 0) {
      return result;
    }
    for (let str of array) {
      if (str.indexOf('=') === -1) {
        continue;
      }
      let kvArr = str.split('=');
      if (kvArr.length < 2) {
        continue;
      }
      let key = kvArr[0];
      let value = kvArr[1];
      result[key] = decodeURIComponent(value);
    }
    return result;
  }
})